<style lang="stylus" rel="stylesheet/stylus">
  @import "../../assets/css/editormd.css"
  @import "../../assets/css/darcula.css"
  .article-post
    .main
      .el-row
        .el-col-20
          .el-form-item
            margin-top 8px
            margin-bottom 6px
            .el-form-item__label
              font-size 20px
            .el-form-item__content
              .el-input
                .el-input__inner
                  font-size 20px
                  border-radius 0
                  border-top none
                  border-left none
                  border-right none
                  border-bottom-width 2px
                  padding-bottom 0
                  background-color #ffffff
            .editor
              box-sizing border-box
              border-top 1px solid rgba(7, 17, 27, .1)
              border-bottom 1px solid rgba(7, 17, 27, .1)
              border-right 1px solid rgba(7, 17, 27, .1)
              .CodeMirror
                border-right-color rgba(7, 17, 27, .1)
              .editormd-toolbar
                border-bottom 1px solid rgba(7, 17, 27, .1)
              .CodeMirror-gutters
                border-right 1px solid rgba(7, 17, 27, .1)
                background-color #ffffff
        .el-col-4
          .el-form
            margin-top 60px
          .el-form-item
            margin-top 25px
            .el-input__inner
              border-radius 0
              border-top none
              border-left none
              border-right none
            &:nth-child(1)
              .el-button
                width 90%
            &:nth-child(3)
              .el-checkbox
                width 100%
              .el-checkbox + .el-checkbox
                margin-left 0
            &:nth-child(4)
              .el-tag
                margin-left 5px
            &:nth-child(5)
              .el-tag
                cursor pointer
                margin-left 5px
</style>

<template>
  <div class="article-post">
    <el-breadcrumb>
      <el-breadcrumb-item :to="'/'">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="'/layout/article'">文章</el-breadcrumb-item>
      <el-breadcrumb-item>发布</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="main">
      <el-form ref="form" :model="form" label-width="80px" @submit.native.prevent>
        <el-row>
          <el-col :span="20">
            <el-row type="flex" justify="center">
              <el-col :span="15">
                <el-form-item label="标题">
                  <el-input v-model.trim="form.title"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <div id="mdeditor" class="editor"></div>
          </el-col>
          <el-col :span="4" v-show="rightBarVisible">
            <el-form :model="form" ref="form" label-width="60px" @submit.native.prevent>
              <el-form-item>
                <el-button type="primary" :loading="postLoading" @click="post">保存</el-button>
              </el-form-item>
              <el-form-item label="类型">
                <el-radio class="radio" v-model="form.type" label="1">正式</el-radio>
                <el-radio class="radio" v-model="form.type" label="2">草稿</el-radio>
              </el-form-item>
              <el-form-item label="分类">
                <el-checkbox-group v-model="form.categoryNames">
                  <el-checkbox v-for="category in categories" :label="category.name" :key="category.id"></el-checkbox>
                </el-checkbox-group>
                <el-input
                  v-if="categoryInputVisible"
                  v-model.trim="categoryInputValue"
                  ref="categoryInput"
                  size="mini"
                  @keyup.enter.native="addCategory"
                  @blur="addCategory"
                ></el-input>
                <el-button v-else size="small" @click="showCategoryInput()">添加分类</el-button>
              </el-form-item>
              <el-form-item label="标签">
                <el-tag
                  :key="tagName"
                  v-for="tagName in form.tagNames"
                  :closable="true"
                  :close-transition="false"
                  @close="closeTag(tagName)"
                >{{tagName}}
                </el-tag>
                <el-input
                  v-if="tagInputVisible"
                  v-model.trim="tagInputValue"
                  ref="tagInput"
                  size="mini"
                  @keyup.enter.native="addTag"
                  @blur="addTag"
                ></el-input>
                <el-button v-else size="small" @click="showTagInput">添加标签</el-button>
              </el-form-item>
              <el-form-item label="选择">
                <el-tag type="primary" v-for="tag in tags" :key="tag.id" @click.native="selectTag(tag.name)">{{tag.name}}
                </el-tag>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
  import util from '../../assets/js/util'
  import '../../assets/js/editormd'
  export default{
    data(){
      return {
        form: {
          id: '',
          title: '',
          type: '1',
          categoryNames: [],
          tagNames: [],
          mdContent: '',
          htmlContent: '',
          categoryIds: [],
          tagIds: []
        },
        rightBarVisible: true,
        categories: [],
        tags: [],
        tagInputVisible: false,
        tagInputValue: '',
        postLoading: false,
        categoryInputVisible: false,
        categoryInputValue: ''
      }
    },
    methods: {
      post(){
        this.postLoading = true
        this.form.categoryIds = []
        for (let categoryName of this.form.categoryNames) {
          for (let category of this.categories) {
            if (categoryName === category.name)
              this.form.categoryIds.push(category.id)
          }
        }
        this.form.tagIds = []
        let tempTagId
        for (let tagName of this.form.tagNames) {
          tempTagId = 0
          for (let tag of this.tags) {
            if (tagName === tag.name)
              tempTagId = tag.id
          }
          this.form.tagIds.push(tempTagId)
        }
        this.form.mdContent = util.editor.getMarkdown()
        this.form.htmlContent = util.editor.getPreviewedHTML()
        util.api.post('/api/admin/saveArticle', this.form)
          .then(data => {
            if (data.isOk) {
              this.$message.success('保存成功')
              this.$router.push('/layout/article')
            } else {
              this.$message.error(data.errmsg)
            }
            this.postLoading = false
          })
          .catch(() => {
            this.postLoading = false
          })
      },
      loadEditData(){
        let articleId = this.$route.params.articleId
        if (articleId) {
          this.form.id = articleId
          util.api.post('/api/admin/editArticle', {articleId: articleId})
            .then(data => {
              if (data.isOk) {
                this.form.title = data.title
                this.form.type = data.type
                this.form.categoryNames = data.categoryNames
                this.form.tagNames = data.tagNames
                util.editor.setMarkdown(data.mdContent)
              } else {
                this.$message.error(data.errmsg)
              }
            })
        } else {
          this.form.id = ''
          this.form.title = ''
          this.form.type = '1'
          this.form.categoryNames = []
          this.form.tagNames = []
          util.editor.setMarkdown('')
        }
      },
      getCategories(){
        util.api.post('/api/admin/getCategories')
          .then(data => {
            if (data.isOk) {
              this.categories = data.categories
            } else {
              this.$message.error(data.errmsg)
            }
          })
      },
      getTags(){
        util.api.post('/api/admin/getTags')
          .then(data => {
            if (data.isOk) {
              this.tags = data.tags
            } else {
              this.$message.error(data.errmsg)
            }
          })
      },
      selectTag(tagName){
        if (this.form.tagNames.indexOf(tagName) === -1)
          this.form.tagNames.push(tagName)
      },
      closeTag(tagName) {
        this.form.tagNames.splice(this.form.tagNames.indexOf(tagName), 1)
      },
      showTagInput() {
        this.tagInputVisible = true
        this.$nextTick(_ => {
          this.$refs.tagInput.$refs.input.focus()
        })
      },
      addTag() {
        let tagInputValue = this.tagInputValue;
        if (tagInputValue) {
          if (this.form.tagNames.indexOf(tagInputValue) === -1)
            this.form.tagNames.push(tagInputValue)
        }
        this.tagInputVisible = false
        this.tagInputValue = ''
      },
      showCategoryInput(){
        this.categoryInputVisible = true
        this.$nextTick(_ => {
          this.$refs.categoryInput.$refs.input.focus()
        })
      },
      addCategory(){
        let categoryInputValue = this.categoryInputValue
        if (categoryInputValue) {
          let has = false
          for (let category of this.categories) {
            if (category.name === categoryInputValue)
              has = true
          }
          if (!has) {
            let category = {id: 0, name: categoryInputValue}
            this.categories.push(category)
          }
        }
        this.categoryInputVisible = false
        this.categoryInputValue = ''
      },
      initEditor(){
        let _this = this
        util.editor = new editormd("mdeditor", {
          width: "100%",
          height: 690,
          toolbarIcons: function () {
            return [
              "undo", "redo", "|",
              "bold", "del", "italic", "quote", "|",
              "h1", "h2", "h3", "h4", "h5", "h6", "|",
              "list-ul", "list-ol", "hr", "|",
              "link", "image", "code", "code-block", "table", "datetime", "html-entities", "|",
              "goto-line", "watch", "preview", "fullscreen", "clear", "search", "|",
              "help"
            ]
          },
          path: '../../static/editormd/lib/',
          pageBreak: false,
          codeFold: true,
          taskList: true,
          flowChart: true,
          sequenceDiagram: true,
          placeholder: '开始你的MarkDown写作...',
          htmlDecode: "style,script",
          atLink: false,
          emailLink: false,
          imageUpload: true,
          imageUploadURL: util.serverUrl + '/resource/uploadForMDEditor?authcode=' + util.authcode,
          crossDomainUpload: true,
          uploadCallbackURL: location.protocol + "//" + location.host + '/static/upload_callback.html',
          onfullscreen: function () {
            _this.rightBarVisible = false
            $('.layout-copy').css('display', 'none')
          },
          onfullscreenExit: function () {
            _this.rightBarVisible = true
            $('.layout-copy').css('display', 'block')
          },
          onload: function () {
            _this.loadEditData();
            util.editor.loaded = true
          }
        })
      }
    },
    mounted(){
      this.initEditor()
    },
    activated(){
      this.getCategories()
      this.getTags()
      if (util.editor.loaded) {
        this.loadEditData()
      }
    }
  }
</script>
